#include <iostream>
#include "httplib.hpp"
#include "add_contacts.pb.h"

using namespace std;
using namespace httplib;

void printContact(add_contact::AddContactRequest& req)
{
    cout << "联系人姓名: " << req.name() << endl;
    cout << "联系人年龄: " << req.age() << endl;
    for(int j=0; j<req.phone_size(); j++)
    {
        const add_contact::AddContactRequest_Phone& phone = req.phone(j);
        cout << "联系人电话: " << j + 1 << ":" << req.number();
        cout << "  (" << phone.PhoneType_Name(phone.type()) << ")" << endl;
    }
}

int main()
{
    cout << "-------------服务启动-------------" << endl;
    Server server;
    
    server.Post("/contacts/add", [](const Request& req, Response& res){
        cout << "接收到post请求" << endl;
        // 反序列化 request: req.body
        add_contact::AddContactRequest request;
        add_contact::AddContactResponce response;
        if(!request.ParseFromString(req.body)){
            cout << "AddContactRequest 反序列化失败" << endl;
        }
        // 新增联系人, 持久化存储通讯录=》打印新增的联系人信息
        printContact(request);

        // 构造 response: res.body
        response.set_success(true);
        response.set_uid();

        // res.body 序列化
        string resp_str;
        if(!response.SerializeToString(&resp_str)){
            cout << "AddContactResponce 序列化失败" << endl;
        }
        res.status = 200;
        res.body = resp_str;
        res.set_header("Content-Type", "application/protobuf");
    });

    // 绑定8123端口
    server.listen("0.0.0.0", 8123);

    return 0;
}

// int main()
// {
//     cout << "-------------服务启动-------------" << endl;
//     Server server;
    
//     server.Post("/test-post", [](const Request& req, Response& res){
//         cout << "接收到post请求" << endl;
//         res.status = 200;
//     });

//     server.Get("/test-get", [](const Request& req, Response& res){
//         cout << "接收到get请求" << endl;
//         res.status = 200;
//     });

//     // 绑定8123端口
//     server.listen("0.0.0.0", 8123);

//     return 0;
// }